﻿using System.Collections.Generic;
using System.Linq;
using Raven.Client;

namespace Mailias.UI.Web.Models
{
    public class MessagesIndexViewModel
    {
        public List<Message> MessageList { get; set; }
        public int StartAt { get; set; }
        public int Count { get; set; }

        public static MessagesIndexViewModel Create(IDocumentSession session, int startAt=0, int count = 20)
        {
            var result = new MessagesIndexViewModel();

            result.MessageList = session.Query<Message>().OrderByDescending(m => m.CreatedOn)
                .Skip(startAt)
                .Take(count)
                .ToList();

            return result;
        }

        public static MessagesIndexViewModel CreateForUser(IDocumentSession session, string currentUserName, int startAt = 0, int count = 20)
        {
            var result = new MessagesIndexViewModel();

            var currentSubscriptions = session.Query<Subscription>().Where(s => s.Username == currentUserName);
            List<Message> subscribedMessages = new List<Message>();

            currentSubscriptions.ToList().ForEach(s =>
                                                  subscribedMessages.AddRange(
                                                      session.Query<Message>().Where(m => m.To == s.To).ToList())
                );

             result.MessageList = subscribedMessages.Distinct()
                 .OrderByDescending(m => m.CreatedOn)
                .Skip(startAt)
                .Take(count)
                .ToList();

            return result;
        }
    }

}